package com.hj.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hj.entity.AcctUser;

/**
 * 安全相关实体的管理类,包括用户和权限组.
 * 
 * @author calvin
 */
//Spring Bean的标识.
@Service
//默认将类中的所有public函数纳入事务管理.
@Transactional
public class AccountManager {

	private Logger log = LogManager.getLogger(getClass());
	@Autowired
	private UserDao userDao;

	@PersistenceContext
	private EntityManager em;
	//-- User Manager --//
	public AcctUser getUser(Long id) {
		AcctUser u=userDao.findOne(id);
		Hibernate.initialize(u.getAcctGroups());
//		log.info(u.getAcctGroups().size());
		return u;
	}

	public void saveUser(AcctUser entity) {
		userDao.save(entity);
//		em.persist(entity);
//		Query query= em.createQuery("select u from User u where u.loginName=?");
//		query.setParameter(1, "huangjian");
//		List l =query.getResultList();
//		log.info(l.size());
//		User u =em.find(User.class, 16l);
//		log.info(u);
	}

	/**
	 * 删除用户,如果尝试删除超级管理员将抛出异常.
	 */
	public void deleteUser(Long id) {
		if (isSupervisor(id)) {
			log.warn("操作员{}尝试删除超级管理员用户");
			throw new ServiceException("不能删除超级管理员用户");
		}
		userDao.delete(id);
	}
	public void delete(AcctUser entity){
//		userDao.delete(entity);
		em.remove(em.merge(entity));
//		User user=em.merge(entity);
//		em.remove(entity);
	}
	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(Long id) {
		return id == 1;
	}

	public List<AcctUser> getAllUser() {
		return (List<AcctUser>) userDao.findAll(new Sort(Direction.ASC, "id"));
	}
	public Page<AcctUser> getPageUser(){
		return userDao.findAll(new PageRequest(0, 20));
	}

	public AcctUser findUserByLoginName(String loginName) {
		return userDao.findByLoginName(loginName);
	}

}
